package com.sensePlusVR.main;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.sensePlusVR.realGame.VideoGamePlayer;
import com.sensePlusVR.utils.AppUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.ScreenListener;
import com.sensePlusVR.utils.ScreenListener.ScreenStateListener;
import com.senseplusvr.sdk.videoview.HemiGLView;
import com.senseplusvr.sdk.videoview.SvrBaseGLView;
import com.senseplusvr.sdk.videoview.SvrConstant;
import com.senseplusvr.sdk.videoview.SvrConstant.UIImageTipAlignment;
import com.senseplusvr.sdk.videoview.SvrInterf;
//import com.example.awsdemo.BluetoothPlayer.BTDepth;

@SuppressLint({ "InlinedApi", "NewApi" })
@SuppressWarnings("unused")
public class VrRealActivity extends VrRealBaseActivity {
	private static final String TAG = "VrRealActivity";
	private VideoGamePlayer mPlayer;
	private SvrBaseGLView mRenderView;
	private SurfaceTexture nativeTexture;

	private Object mFadeLock;
	private int mPlayMode;
	private List<String> mConfigList;
	private int mCurrentConfig;
	public static final int PLAYER_START = 0;
	public static final int PLAYER_ACTION = 1;
	public static final int PLAYER_END = 2;
	public static final int PLAYER_DES = 3;
	private static final int VR_180_mono = 1;
	private static final int VR_180_lf   = 3;
	private static final int NORMAL_mono     = 2;
	private static final int VR_360_mono = 4;
	private static final int VR_360_lf   = 5;
	
	private static final int NORMAL_lf       = 6;
	private int mCurrentPlayer;
	private float value = 0;
	private final float alpha = 0.49f;
	private boolean mRenderViewLocked = false;
	private boolean mFading = false;
	private boolean mIsInterActiveMode = false;
	private ScreenListener screenListener = new ScreenListener(this);
	private boolean mIsNear = false;
	@Override
	protected void onCreate(Bundle bundle) {
		// TODO Auto-generated method stub
		super.onCreate(bundle);
		AppUtil.hideVirtualKey(this);
		init();
//		AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
//		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
//				mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) - 2,
//				AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
		screenListener.begin(new ScreenStateListener() {

	        @Override
	        public void onUserPresent() {
	        	mPlayer.resume();
	        }

	        @Override
	        public void onScreenOn() {
	            
	        }

	        @Override
	        public void onScreenOff() {
	        	MyLog.e(TAG, "screen off....");
	        	mPlayer.pause();
	        }
	    });
	}
	

	private void init() {
		mFadeLock = new Object();
		String sdpath = Environment.getExternalStorageDirectory().getPath(); 
		Log.e(TAG, "sdpath:");
		//String testConfigPath = sdpath + "/new/videoGame.json";
		String[] gameconfig = getGameConfig();
		Log.e(TAG, "config=" + gameconfig);
		if (gameconfig == null)
			return;
		mCurrentConfig = 0;
		mCurrentPlayer = PLAYER_START;
		mConfigList = new ArrayList<String>();

		for (String config : gameconfig) {
			//Log.e(TAG, "config=" + testConfigPath);
			//mConfigList.add(testConfigPath);
			mConfigList.add(config);
		}
		mPlayer = new VideoGamePlayer(this);
		mPlayer.create(mConfigList.get(mCurrentConfig));
		mPlayer.setGameEventListener(mGameCallBack);

		mRenderView = getHemiGlView();
		
		mRenderView.setGraidentCallback(mGradientCallback);
		int sourcetype = mPlayer.getSourceType();
		
		MyLog.d(TAG, "sourcetype ： " + sourcetype);
		
		if (sourcetype == VR_180_mono || sourcetype == NORMAL_mono)
			mRenderView.setInputVideoType(SvrConstant.InputVideoType.InputVideo_MONO);
		else if (sourcetype == VR_180_lf)
			mRenderView.setInputVideoType(SvrConstant.InputVideoType.InputVideo_LR);
		
		//显示Tip
		showInteractiveUI(mIsInterActiveMode, false,false);
		mRenderView.setDrawFrameCallback(new SvrInterf.DrawFrameCallback() {

			@Override
			public void onFrameUpdate() {
				// TODO Auto-generated method stub
				// Log.e(TAG, "update "+System.currentTimeMillis());
				float alpha = mPlayer.showActionFrame();
				if (alpha != -1.0f){
					Log.e(TAG, "set alpha="+alpha);
					mRenderView.setAlpha(alpha);
				}
			}

		});
	}

	@Override
	public void onSurfaceTexture(SurfaceTexture surfacetexture) {
		// TODO Auto-generated method stub
		super.onSurfaceTexture(surfacetexture);

		Log.e(TAG, "surface=" + surfacetexture);
		nativeTexture = surfacetexture;
		mPlayer.setPlayerSurface(nativeTexture);
		mPlayer.Play();// start to play
	}

	@Override
	public void onSurfaceTexture2(SurfaceTexture surfacetexture) {
		// TODO Auto-generated method stub
		super.onSurfaceTexture2(surfacetexture);
		Log.e(TAG, "onSurfaceTexture2=" + surfacetexture);
		mPlayer.setBlendSurface(surfacetexture);
	}


	@Override
	protected void onDataReceived(float depth, float freq, float smoothFactor) {
		// TODO Auto-generated method stub
		super.onDataReceived(depth, freq, smoothFactor);

		value = value * (1.0f - alpha) + (float) depth * (alpha);
			// Log.e(TAG, "onDepth:"+depth+" filted="+value);
		synchronized(this){
			if (mPlayer != null)
				mPlayer.setDepth((float) value);
		}
	}

	private void PlayNext(){
		mPlayer.NextAction();
		PlayCurrent();
	}
	
	private void PlayCurrent(){
		if (mPlayer.CurrentActionIsVideo()){
			if (mIsInterActiveMode){
				mIsInterActiveMode = false;
				showInteractiveUI(mIsInterActiveMode);
			}
			PlayDesVideo();
		}else{
			if (!mIsInterActiveMode){
				mIsInterActiveMode = true;
				showInteractiveUI(mIsInterActiveMode);
			}
			PlayAction();			
		}
	}
	/*
	 *对应飞机杯的max一次按键
	 *对应手环的一次按键
	 */
	@Override
	protected void onMaxKeyClick() {
		Log.e(TAG, "change action....");
		synchronized(this){
			if (mCurrentPlayer == PLAYER_START){
				if (!mPlayer.supportVideoMode()){
					PlayCurrent();
					return;
				}
				PlayDesVideo();
	            mIsInterActiveMode = false;   
	            return;
			}
			setNextTipVisible(true, 1.0f);
			if (!mPlayer.supportVideoMode()){
				PlayNext();
				return;
			}
			
			if (mIsInterActiveMode){
				PlayNextAction();
			}else
			{
				PlayNextDesVideo();
			}
		}
	}

	/*
	 *对应飞机杯的max长按
	 *对应手环的长按
	 */
	@Override
	protected void onMaxKeyLongPress() {
		Log.e(TAG, "play end video");
		mPlayer.LastAction();
		PlayEnd();
	}
	
	/*
	 *对应飞机杯的Option key
	 *对应手环的double click
	 */
	@Override
	protected void onOptionKeyClick() {
		
		if (!mPlayer.supportVideoMode())
			return;
		synchronized(this){
			mIsInterActiveMode = !mIsInterActiveMode;
			//显示Tip
			showInteractiveUI(mIsInterActiveMode);
			if (mIsInterActiveMode){
				PlayAction();
				Log.e(TAG, "change video to action mode");
			}else{
				PlayDesVideo();
				Log.e(TAG, "change action to video mode");
			}
		}
	}

	/*
	 *对应飞机杯的Option key 长按
	 *对应手环的triple click
	 */
	@Override
	protected void onOptinKeyLongPress() {
		// mRenderView
		if (mRenderViewLocked) {
			// unlock;
			
			mRenderView.recenterTracking();
			mRenderViewLocked = false;
		} else {
			// lock
			mRenderView.pauseTracking();
			mRenderViewLocked = true;
		}
	}

	@Override
	protected void onChangeMinor(){
		synchronized(this){
			if (mCurrentPlayer == PLAYER_ACTION){
				Log.e(TAG, "onChangeMinor");
				mIsNear = !mIsNear;
				set2DNear(mIsNear);
				mPlayer.changePlayMinor();
			}
		}
	}
	private SvrInterf.GradientCallback mGradientCallback = new SvrInterf.GradientCallback() {
		@Override
		public void onGradient(float alpha, boolean isAdd) {
			if (!isAdd && alpha == 0.0f) {
				DoFade();
			}else {
        		if (isAdd && alpha == 1.0f){
        			
        			setNextTipVisible(false, 1.0f);
        			mRenderView.setUIImageAlignment(UIImageTipAlignment.Alignment_Default);
        			//showInteractiveUI(false, false, false);
        			FadeFinish();
        		}
        	}
		}
	};
	
	private synchronized void FadeFinish(){
		mFading = false;
	}
	private void PlayNextGameFade(){
		mCurrentConfig = (mCurrentConfig + 1) % mConfigList.size();
		mPlayer.release();
		mPlayer.create(mConfigList.get(mCurrentConfig));
		mPlayer.PlayStartVideo();
		mCurrentPlayer = PLAYER_START;
	}
	   
    private synchronized void PlayNextGame(){
    	PlayFadinOut(VideoGamePlayer.PLAY_NEXT_GAME, 3.0f, 1.0f);
    }
    
	private synchronized void PlayNextAction() {
		//if (mCurrentPlayer != PLAYER_END)
		PlayFadinOut(VideoGamePlayer.PLAY_NEXT_ACTION, 3.0f, 1.0f);
	}
	
	private synchronized void PlayNextDesVideo() {
		PlayFadinOut(VideoGamePlayer.PLAY_NEXT_VIDEO, 3.0f, 1.0f);
	}

	
	private synchronized void PlayDesVideo()
	{
		//if (mCurrentPlayer != PLAYER_END)
		PlayFadinOut(VideoGamePlayer.PLAY_VIDEO, 3.0f, 1.0f);
	}

	private synchronized void PlayEnd() {
		if (mCurrentPlayer != PLAYER_END){
			//显示Tip
			if (mIsInterActiveMode){
				mIsInterActiveMode = false;
				showInteractiveUI(mIsInterActiveMode); 
			}
			PlayFadinOut(VideoGamePlayer.PLAY_MODE_END, 3.0f, 1.0f);
		}
	}

	private synchronized void PlayAction() {
		Log.e(TAG, "play action in activity");
		PlayFadinOut(VideoGamePlayer.PLAY_ACTION, 3.0f, 1.0f);
	}

	private void PlayFadinOut(int mode, float in, float black) {
		//if (!mFading)
		{
			mFading = true;
			mPlayMode = mode;
			mRenderView.startGradient(in, black);
		}
	}

//	private void wait(int wait) {
//		try {
//			Thread.sleep(wait);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	
	private synchronized void changeMinor(){
		mPlayer.changePlayMinor();
	}

	private void resetToFar(){
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				synchronized(VrRealActivity.this){
					if (mIsNear){
						mIsNear = false;
						set2DNear(mIsNear);
					}
				}
			}
			
		});

	}
	private synchronized void DoFade() {
		if (isDestroyed())
			return;
		int prePlayer = mCurrentPlayer;
		if (mPlayMode == VideoGamePlayer.PLAY_ACTION) {
			Log.e(TAG, "play action current="+mCurrentPlayer);
			if (mCurrentPlayer != PLAYER_ACTION){
				mPlayer.stopVideoPlay();
			}else{
				mPlayer.stopActionPlay();
			}
			
			if (mCurrentPlayer == PLAYER_END || mCurrentPlayer == PLAYER_DES){
				mPlayer.startWomanAudio();
			}
			mPlayer.PlayAction();
			resetToFar();
			mCurrentPlayer = PLAYER_ACTION;
		} else if (mPlayMode == VideoGamePlayer.PLAY_NEXT_ACTION) {
			Log.e(TAG, "play next action current="+mCurrentPlayer);
			if (mCurrentPlayer != PLAYER_ACTION){
				mPlayer.stopVideoPlay();
			}else{
				mPlayer.stopActionPlay();
			}
			if (mCurrentPlayer == PLAYER_START)
				mPlayer.PlayAction();
			else
				mPlayer.PlayNextAction();
			resetToFar();
			mCurrentPlayer = PLAYER_ACTION;
		} else if (mPlayMode == VideoGamePlayer.PLAY_MODE_END) {
			/*
			 * when change action to play end, we need stop and release action
			 * player and then start end video play, or the android_window is
			 * not release , so end video player can not create mediacodec
			 */
			Log.e(TAG, "play end current="+mCurrentPlayer);
			if (mCurrentPlayer == PLAYER_START) {
				Log.e(TAG, "stop start video");
				mPlayer.stopVideoPlay();
				Log.e(TAG, "stop start video ok");
			} else {
				if (mCurrentPlayer == PLAYER_ACTION)
					mPlayer.stopActionPlay();
				mPlayer.releaseActionPlay();
				mPlayer.stopWomanAudio();
			}
			Log.e(TAG, "play end video");
			mPlayer.PlayEndVideo();
			Log.e(TAG, "play end video ok");
			mCurrentPlayer = PLAYER_END;
		}else if (mPlayMode == VideoGamePlayer.PLAY_NEXT_GAME){
			PlayNextGameFade();
		}
		else if (mPlayMode == VideoGamePlayer.PLAY_NEXT_VIDEO)
		{
			Log.e(TAG, "play next video current="+mCurrentPlayer);
			if (mCurrentPlayer == PLAYER_ACTION){
				mPlayer.stopActionPlay();
				mPlayer.releaseActionPlay();
			}else if (mCurrentPlayer == PLAYER_DES){
				mPlayer.stopVideoPlay();
            }
			mPlayer.PlayNextDesVideo();
			mCurrentPlayer = PLAYER_DES;
		}
		else if (mPlayMode == VideoGamePlayer.PLAY_VIDEO)
		{
			Log.e(TAG, "play video current="+mCurrentPlayer);
			if (mCurrentPlayer == PLAYER_ACTION){
				mPlayer.stopActionPlay();
				mPlayer.releaseActionPlay();
				mPlayer.stopWomanAudio();
			}else{
				mPlayer.stopVideoPlay();
			}
			mPlayer.PlayDesVideo();
			mCurrentPlayer = PLAYER_DES;
		}
		
		setPlayerMode(prePlayer,mCurrentPlayer);
	}
	
	
	private void currentGameFinished() {
		if (mConfigList.size() == 1)
		{
			if (!mPlayer.supportVideoMode())
				PlayNext();
			else
				PlayNextDesVideo();
		}
		else {
			PlayNextGame();
		}
	}

	private VideoGamePlayer.GameEvent mGameCallBack = new VideoGamePlayer.GameEvent() {

		@Override
		public void onEvent(int event, int arg0, int arg1) {
			// TODO Auto-generated method stub
			synchronized (this) {

				if (event == VideoGamePlayer.GAME_EVENT_VIDEO_WILL_END) {
					if(!mPlayer.supportVideoMode()){
						if (mCurrentPlayer == PLAYER_START){
							PlayCurrent();
						}else if (mCurrentPlayer == PLAYER_END){
							currentGameFinished();
						}else{
							PlayNext();
						}
					}else{
						if (mCurrentPlayer == PLAYER_START){
							PlayDesVideo();
						}else if (mCurrentPlayer == PLAYER_END){
							currentGameFinished();
						}else{
							PlayNextDesVideo();
						}
					}
				} else if (event == VideoGamePlayer.GAME_EVENT_FINISHED) {
					currentGameFinished();
				} else if (event == VideoGamePlayer.GAME_EVENT_PLAY_VIDEO) {
					if (mCurrentPlayer == PLAYER_START)
						PlayDesVideo();
					else
						PlayNextDesVideo();
				}
			}
		}

	};
	
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mPlayer.pause();
	}

	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mPlayer.resume();
	}
	
	@Override
	protected synchronized void onDestroy() {
		super.onDestroy();
		screenListener.unregisterListener();
		mPlayer.release();
	}
}
